package info.wangyuan.agent.controller.portal;


import info.wangyuan.agent.common.Enum.MsgEnum;
import info.wangyuan.agent.config.UserContext;
import info.wangyuan.agent.entity.po.User;
import info.wangyuan.agent.service.curd.UserService;
import info.wangyuan.agent.utils.JwtUtils;
import info.wangyuan.agent.utils.Result;
import info.wangyuan.agent.utils.WechatUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery;

/**
 * 微信登录控制器
 *
 * @author Albert
 * @since 2025-09-11 18:54:33
 */
@Slf4j
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/wx")
public class UserController {

    private final UserService userService;
    private final JwtUtils jwtUtils;

    public UserController(UserService userService, JwtUtils jwtUtils) {
        this.userService = userService;
        this.jwtUtils = jwtUtils;
    }

    private static final String STATE = "agent";

    /**
     * 蓝宝AI应用回调地址（便于前端获取公众号分配的code）
     */
    @GetMapping("/login")
    public void wxLogin(HttpServletResponse response) throws IOException {
        String url = WechatUtils.getOAuthRedirectUrl(STATE);
        // 重定向 https://wx-app.wangyuan.info/wy_agent/#/?code=081GSG1w3U3OC53Xs82w3H0nP72GSG1r
        response.sendRedirect(url);
    }

    /**
     * 微信回调
     */
    @GetMapping("/info/code")
    public Result<String> getWxCallBack(@RequestParam String code) {
        Map<String, Object> data = WechatUtils.getUserinfoByCode(code);
        if (data == null) {
            return Result.error(MsgEnum.WRONG_WECHAT_CODE);
        }
        String openid = (String) data.get("id");
        User dbUser = userService.getOne(lambdaQuery(User.class).eq(User::getOpenId, openid));
        if (dbUser == null) {
            log.info("新用户: {}", data);
            userService.save(User.builder().openId(openid).build());
        }
        String token = jwtUtils.generateToken(openid);
        return Result.success(token);
    }

    /**
     * 验证登录信息
     */
    @GetMapping("/info/verify/token")
    public Result<Void> checkWxLogin() {
        String openid = UserContext.getCurrentUser().getOpenId();
        User dbUser = userService.getOne(lambdaQuery(User.class).eq(User::getOpenId, openid));
        if (dbUser == null) return Result.error(MsgEnum.WRONG_WECHAT_LOGIN_VERIFY);
        return Result.success();
    }
}
